package com.durian.base.net.request;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.durian.base.net.HttpConfig;
import com.durian.base.net.HttpResponse;
import com.durian.base.net.HttpTaskManager;
import com.durian.base.net.IHttpTask;
import com.durian.base.net.cache.HttpCacheManager;
import com.durian.base.net.cache.IHttpCacheManager;
import com.durian.base.utils.StringUtils;

import java.util.UUID;

/**
 * 说明：AbstractHttpTask
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019/1/30 17:22
 * <p/>
 * 版本：version 1.0
 */
public abstract class AbstractHttpTask implements IHttpTask {

    protected String taskId;
    protected String url;
    protected IHttpCacheManager mHttpCacheManager;
    protected String cacheKey = "";
    protected Lifecycle mLifeCycle;

    public AbstractHttpTask(Lifecycle lifecycle,String url) {
        this.url = url;
        this.mLifeCycle = lifecycle;
        taskId = UUID.randomUUID().toString();
        if (mLifeCycle != null){
            mLifeCycle.addObserver(this);
        }
    }

    @Override
    public void run() {
        try {
            HttpResponse httpResponse;

            doStartTask();

            doHttpMonitorRequest();

            if (HttpConfig.get().getGlobalHttpBlocker() != null){
                httpResponse = HttpConfig.get().getGlobalHttpBlocker().processor(this);
            }else {
                httpResponse = doInBackground();
            }

            if (httpResponse == null){
                httpResponse = HttpResponse.nullResponse();
            }
            if (httpResponse.isSuccess()){
                doSuccessTask(httpResponse);
                HttpCacheManager.saveCache(this,httpResponse.getResult());
            }else {
                String result = HttpCacheManager.readCache(this);
                if (StringUtils.isNotEmpty(result)){
                    httpResponse = HttpResponse.fromCache(httpResponse,result);
                    doSuccessTask(httpResponse);
                }else {
                    doErrorTask(httpResponse.getErrorCode(),httpResponse.getException());
                }
            }

            HttpTaskManager.get().removeTask(this);
            doHttpMonitorResponse(httpResponse);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    protected void doHttpMonitorRequest(){}

    protected void doHttpMonitorResponse(HttpResponse response){}

    protected HttpResponse doInBackground() {
        return HttpResponse.nullResponse();
    }

    /**
     * 任务成功
     */
    protected void doSuccessTask(final HttpResponse response){
        if (mLifeCycle != null) {
            if (mLifeCycle.getCurrentState().isAtLeast(Lifecycle.State.CREATED)) {
                HttpTaskManager.get().getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        onSuccessTask(response);
                    }
                });
            }
        } else {
            HttpTaskManager.get().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    onSuccessTask(response);
                }
            });
        }
    }

    /**
     * 任务错误
     * @param errorCode
     * @param e
     */
    protected void doErrorTask(final int errorCode,final Exception e){
        if (mLifeCycle != null) {
            if (mLifeCycle.getCurrentState().isAtLeast(Lifecycle.State.CREATED)) {
                HttpTaskManager.get().getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        onErrorTask(errorCode, e);
                    }
                });
            }
        } else {
            HttpTaskManager.get().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    onErrorTask(errorCode, e);
                }
            });
        }
    }

    /**
     * 开始执行任务
     */
    protected void doStartTask(){
        if (mLifeCycle != null) {
            if (mLifeCycle.getCurrentState().isAtLeast(Lifecycle.State.CREATED)) {
                HttpTaskManager.get().getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        onStartTask();
                    }
                });
            }
        } else {
            HttpTaskManager.get().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    onStartTask();
                }
            });
        }
    }

    @Override
    public String getUrl() {
        return url;
    }

    @Override
    public String getTaskId() {
        return taskId;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    @Override
    public void cancelTask() {
        HttpTaskManager.get().removeTask(this);
        if (mLifeCycle != null){
            mLifeCycle.addObserver(this);
        }
        doCancelTask();
    }

    /**
     * 取消任务执行
     */
    protected void doCancelTask(){ }
}
